﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Standard;
using VCommons;
using System.Web.Routing;


namespace Web.Attributes
{

    /// <summary>
    /// 用户验证列举
    /// </summary>
    public enum AuthenticationType
    {
        /// <summary>
        /// 登录
        /// </summary>
        Login,
        /// <summary>
        /// 后台登陆
        /// </summary>
        BackgroundLogin,
        /// <summary>
        /// 注册
        /// </summary>
        Register,
    }

    /// <summary>
    /// 用户验证过滤器：前台
    /// </summary>
    public class UserAuthentication : AuthorizeAttribute
    {
        public AuthenticationType Authentication { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        public UserAuthentication()
            : this(AuthenticationType.Login) { }
        public UserAuthentication(AuthenticationType authentication)
        {
            this.Authentication = authentication;
        }
        /// <summary>
        /// 执行前验证
        /// </summary>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            //验证不成功的时候
            switch (this.Authentication)
            {
                case AuthenticationType.Login:
                    if (!ClientHelper.Current.HasUserInfo)
                        filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "LogOn" }, { "Controller", "Account" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });
                     break;

                case AuthenticationType.BackgroundLogin:
                    if (string.IsNullOrEmpty(SessionAction.ReadSession("Background_Current_UserID")) || Convert.ToInt32(SessionAction.ReadSession("Background_Current_UserID")) < 0)
                        filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "LogOn" }, { "Controller", "Account" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });
                    break;
                case AuthenticationType.Register:
                    filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Register" }, { "Controller", "Account" } });
                    break;
                default:
                    filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Index" }, { "Controller", "Home" } });
                    break;
            }

        }
    }
}
